<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <title>业务验证</title>

    <!-- placeholders for the theme switcher -->
    <link rel='stylesheet' id='theme_stylesheet'>
    <link rel='stylesheet' id='icon_stylesheet'>

    <style>[class*="foundicon-"] {font-family: GeneralFoundicons;font-style: normal;}</style>
    <script src='jquery-1.9.1.min.js'></script>
    <script src='dist/jsoneditor.js'></script>
    <script src='widget/widgetdef.js'></script>
    <script src='widget/metacommon.js'></script>
    <script src='widget/meta2util.js'></script>
    <script src='widget/meta2content_util.js'></script>
</head>
<body> 
<div class='container'>
    <div class='row' >
        <div class='span8 col-md-8 columns eight large-8' style="width:100%;">
            <h2></h2>
            <p></p>

            <div id='editor'></div>
        </div>
        <div class='span4 col-md-4 columns four large-4'  style="display:none;">
            
            <h2>JSON Output</h2>
            <p>You can also make changes to the JSON here and set the value in the editor by clicking <button class='btn btn-primary' id='setvalue'>Update Form</button></p>
            <textarea id='output--org' style='width: 100%; height: 200px; font-family: monospace;' class='form-control'></textarea>

            <h2>Options</h2>
            <div id='options_holder'>
                <div>
                    <label>CSS Framework</label>
                    <select id='theme_switcher' class='form-control'>
                        <option value='html'>None</option>
                        <option value='jqueryui'>jQuery UI</option>
                        <option value='bootstrap2'>Bootstrap 2</option>
                        <option value='bootstrap3'>Bootstrap 3</option>
                        <option value='foundation3'>Foundation 3</option>
                        <option value='foundation4'>Foundation 4</option>
                        <option value='foundation5'>Foundation 5</option>
                    </select>
                </div>
                <div>
                    <label>Icon Library</label>
                    <select id='icon_switcher' class='form-control'>
                        <option value=''>None</option>
                        <option value='jqueryui'>jQuery UI</option>
                        <option value='bootstrap2'>Bootstrap 2 Glyphicons</option>
                        <option value='bootstrap3'>Bootstrap 3 Glyphicons</option>
                        <option value='foundation2'>Foundicons 2</option>
                        <option value='foundation3'>Foundicons 3</option>
                        <option value='fontawesome3'>FontAwesome 3</option>
                        <option value='fontawesome4'>FontAwesome 4</option>
                    </select>
                </div>
                <div>
                    <label>Object Layout</label>
                    <select id='object_layout' class='form-control'>
                        <option value='normal'>normal</option>
                        <option value='grid'>grid</option>
                    </select>
                </div>
                <div>
                    <label>Show Errors</label>
                    <select id='show_errors' class='form-control'>
                        <option value='interaction'>On Interaction</option>
                        <option value='change'>On Field Change</option>
                        <option value='always'>Always</option>
                        <option value='never'>Never</option>
                    </select>
                </div>
                <div>
                    <label>Boolean options</label>
                    <select multiple size=9 id='boolean_options' style='width: 100%;' class='form-control'>
                        <option value='required_by_default'>Object properties required by default</option>
                        <option value='no_additional_properties'>No additional object properties</option>
                        <option value='ajax'>Allow loading schemas via Ajax</option>
                        <option value='disable_edit_json'>Disable "Edit JSON" buttons</option>
                        <option value='disable_collapse'>Disable collapse buttons</option>
                        <option value='disable_properties'>Disable properties buttons</option>
                        <option value='disable_array_add'>Disable array add buttons</option>
                        <option value='disable_array_reorder'>Disable array move buttons</option>
                        <option value='disable_array_delete'>Disable array delete buttons</option>
                    </select>
                </div>
            </div>

            <h2>Validation</h2>
            <p>This will update whenever the form changes to show validation errors if there are any.</p>
            <textarea id='validate' style='width: 100%; height: 100px; font-family: monospace;' readonly disabled class='form-control'></textarea>
        </div>
        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
                <h2>页面数据模型</h2>
                <p> <button class='btn btn-primary' id='setschema'>更新数据模型定义</button> &nbsp;&nbsp;&nbsp;&nbsp; <button class='btn btn-primary' id='loadSchema'>装载数据模型</button></p>

                <textarea id='schema' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
            </div>
        </div>

        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
                <h2>最终数据模型定义（含运营参数）</h2>
                <p> <button class='btn btn-primary' id='updateContentDef'>更新内容定义页面</button>

                   &nbsp;&nbsp;<input type="button" value="页面数据装载" class='btn btn-primary' id='reloadMetaContent'/></p>

                <textarea id='output' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
            <br/>
            输出schema：
                <textarea id='output_schema' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
            </div>
        </div>
        <div class='span8 col-md-8 columns eight large-8' style="width:100%;">
            <h2>页面内容输入</h2>
            <p>这是最终的页面内容的输入区域</p>

            <div id='contenteditor'></div>
        </div>

        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
            <form method="POST"  action="index.jsp">
                    <h3>最终内容数据 </h3>
                    <h4>
                    | 选择编辑区域：
                    <select id="sltPageArea" >
                        <option value="" selected="">请选择</option>
                    </select>
                    | 选择编辑人员级别：
                    <select id="sltEditorLevel" >                        
                        <option value="" selected="">请选择</option>
                        <option value="1">集团</option>
                        <option value="2">省级</option>
                        <option value="3">地市级</option>
                    </select>
                    </h4>
                 <textarea id='output_cnt'  name="output_cnt" style='width: 100%; height: 200px; font-family: monospace;' class='form-control'></textarea>
                   <p> <button class='btn btn-primary' id='updateContent'>预览页面</button> 
                   &nbsp;&nbsp;<input type="button" value="页面数据装载" class='btn btn-primary' id='reloadContent'/></p>
               </form>
            </div>
        </div>
  
    </div>
</div>       
<script>
schema = {"type":"string","title":"test"};

    // Divs/textareas on the page
    var $schema = document.getElementById('schema');
    var $output = document.getElementById('output');
    var $output_cnt = document.getElementById('output_cnt');
    var $editor = document.getElementById('editor');
    var $validate = document.getElementById('validate');

    var $contenteditor = document.getElementById("contenteditor");

    // Buttons
    var $set_schema_button = document.getElementById('setschema');
    var $load_schema_button = document.getElementById('loadSchema');
    var $load_content_button = document.getElementById("updateContent");
    var $set_value_button = document.getElementById('setvalue');

var gReload = null;
var mark = 1;
(function() {

    // Default starting schema
    if(!schema) {
        schema = {}
    }

    var jsoneditor;
 
    var reload = function(keep_value) {
        var startval = (jsoneditor && keep_value)? jsoneditor.getValue() : window.startval;
        window.startval = undefined;

        if(jsoneditor) jsoneditor.destroy(); 
        jsoneditor = new JSONEditor($editor,{
            schema: schema,
            startval: startval,
            ajax:true,
            disable_edit_json:true,
            disable_properties:true,
            collapse:true

        });
        gReload = reload;
        window.jsoneditor = jsoneditor;

        // When the value of the editor changes, update the JSON output and validation message
        jsoneditor.on('change',function() {
            var json = jsoneditor.getValue();

            $output.value = JSON.stringify(json,null,2);

            var validation_errors = jsoneditor.validate($output.value);
            // Show validation errors if there are any
            if(validation_errors.length) {
                $validate.value = JSON.stringify(validation_errors,null,2);
            }
            else {
                $validate.value = 'valid';
            }
         });
    };

    // Start the schema and output textareas with initial values
    $schema.value = JSON.stringify(schema,null,2);
    $output.value = '';

    // When the 'update form' button is clicked, set the editor's value
    $set_value_button.addEventListener('click',function() {
        jsoneditor.setValue(JSON.parse($output.value));;
    });

    var $metaCntSetting = document.getElementById("reloadMetaContent");
    $metaCntSetting.addEventListener("click",function(){
         jsoneditor.setValue(JSON.parse($output.value));
    });

    // Update the schema when the button is clicked
    $set_schema_button.addEventListener('click',function() {
        try {
            schema = JSON.parse($schema.value);
        }
        catch(e) {
            alert('Invalid Schema: '+e.message);
            return;
        }

        reload();
    });

    $load_schema_button.addEventListener("click",function(){
        try{
            
        if(pagemeta.inited != false ) 
            pagemeta.init();
            $schema.value = "";
            //var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/4gpageMeta_array.json"); //复杂类型
           var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/4gpageMeta.json");   //4G
//             var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/TypeSysShow.json") ;//基础类型
            $schema.value = stringMeta;
        }
        catch(e){         
            alert('error on loading Schema from file: '+e.message);
            throw e;   
        }
    });

    // Set the theme by loading the right stylesheets
    var setTheme = function(theme,no_reload) {
        theme = theme || '';

        var mapping = {
            html: '',
            bootstrap2: '/bootstrap-combined.min.css',
            bootstrap3: 'bootstrap3.2full.css',
            foundation3: '//cdnjs.cloudflare.com/ajax/libs/foundation/3.2.5/stylesheets/foundation.css',
            foundation4: '//cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css',
            foundation5: '//cdn.jsdelivr.net/foundation/5.0.2/css/foundation.min.css',
            jqueryui: '//code.jquery.com/ui/1.10.3/themes/south-street/jquery-ui.css'
        };

        if(typeof mapping[theme] === 'undefined') {
            theme = 'bootstrap3';
            document.getElementById('theme_switcher').value = theme;
        }
        theme = 'bootstrap3';// 
        //theme = 'html';
        JSONEditor.defaults.options.theme = theme;

        document.getElementById('theme_stylesheet').href = mapping[theme];
        document.getElementById('theme_switcher').value = JSONEditor.defaults.options.theme;

        if(!no_reload) reload(true);
    };

    // Set the icontheme
    // Set the theme by loading the right stylesheets
    var setIconlib = function(iconlib,no_reload) {
        iconlib = iconlib || '';
        var mapping = {
            foundation2: '//cdnjs.cloudflare.com/ajax/libs/foundicons/2.0/stylesheets/general_foundicons.css',
            foundation3: '//cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/foundation-icons.css',
            fontawesome3: '/font-awesome.css',
            fontawesome4: '/font-awesome.css'
        };

        JSONEditor.defaults.options.iconlib = iconlib;

        document.getElementById('icon_stylesheet').href = mapping[iconlib] || '';
        document.getElementById('icon_switcher').value = JSONEditor.defaults.options.iconlib;

        if(!no_reload) reload(true);
    };

    var refreshBooleanOptions = function(no_reload) {
        var boolean_options = document.getElementById('boolean_options').children;
        for(var i=0; i<boolean_options.length; i++) {
            JSONEditor.defaults.options[boolean_options[i].value] = boolean_options[i].selected;
        }
        if(!no_reload) reload(true);
    };

    // Change listeners for options
    document.getElementById('theme_switcher').addEventListener('change',function() {
        setTheme(this.value);
    });
    document.getElementById('icon_switcher').addEventListener('change',function() {
        setIconlib(this.value);
    });
    document.getElementById('object_layout').addEventListener('change',function() {
       JSONEditor.defaults.options.object_layout = this.value;
        reload(true);
    });
    document.getElementById('show_errors').addEventListener('change',function() {
       JSONEditor.defaults.options.show_errors = this.value;
        reload(true);
    });
    document.getElementById('boolean_options').addEventListener('change',function() {
        refreshBooleanOptions();
    });
    
  
    // Set options from direct link
    setTheme((window.location.href.match(/[?&]theme=([^&]+)/)||[])[1] || 'bootstrap2', true);
    
    setIconlib((window.location.href.match(/[?&]iconlib=([^&]*)/)||[null,'none'])[1], true);
    
    document.getElementById('object_layout').value = (window.location.href.match(/[?&]object_layout=([^&]+)/)||[])[1] || 'normal';
    JSONEditor.defaults.options.object_layout = document.getElementById('object_layout').value;
    
    document.getElementById('show_errors').value = (window.location.href.match(/[?&]show_errors=([^&]+)/)||[])[1] || 'interaction';
    JSONEditor.defaults.options.show_errors = document.getElementById('show_errors').value;
    
    var boolean_options = document.getElementById('boolean_options').children;
    for(var i=0; i<boolean_options.length; i++) {
        if(window.location.href.match(new RegExp('[?&]'+boolean_options[i].getAttribute('value')+'([&=]|$)'))) {
            boolean_options[i].selected = true;
        }
    }
    refreshBooleanOptions(true);
    
    // Custom validators must return an array of errors or an empty array if valid
JSONEditor.defaults.custom_validators.push(function(schema, value, path) {
  var errors = [];
  if(schema.format==="date2") {
    if(!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)) {
      // Errors must be an object with `path`, `property`, and `message`
      errors.push({
        path: path,
        property: 'format',
        ajax:"true",
        message: 'Dates must be in the format "YYYY-MM-DD"'
      });
    }
  }
  return errors;
});

//    reload();
})();


//content editor area:
    var jsoneditor_cnt;

    var cnt_schema = {"type":"string","title":"test"};

    var reload_cnt = function(keep_value) {
        var startval = (jsoneditor_cnt && keep_value)? jsoneditor_cnt.getValue() : window.startval;
        window.startval = undefined;

         if(jsoneditor_cnt) jsoneditor_cnt.destroy();
        jsoneditor_cnt = new JSONEditor($contenteditor,{
            schema: cnt_schema,
            startval: startval,
            ajax:true,
            disable_edit_json:true,
            disable_properties:true,
            collapse:true
        });
        window.jsoneditor_cnt = jsoneditor_cnt;
        jsoneditor_cnt.on("ready",postReadyFunc);

        // When the value of the editor changes, update the JSON output and validation message
        jsoneditor_cnt.on('change',function() {
            var json = jsoneditor_cnt.getValue();

            $output_cnt.value = JSON.stringify(json,null,2);

            var validation_errors = jsoneditor_cnt.validate();
            // Show validation errors if there are any
            if(validation_errors.length) {
                //$validate.value = JSON.stringify(validation_errors,null,2);
//                 console.log("content json validate result: " + JSON.stringify(validation_errors,null,2));
            }
            else {
                //$validate.value = 'valid';
                console.log("content json validate result: valid!")
            }
         });
    };


/*
    // Update the schema when the button is clicked
    $load_content_button.addEventListener('click',function() {
        try {
            cnt_schema = JSON.parse($schema.value);
        }
        catch(e) {
            alert('Invalid Schema: '+e.message);
            return;
        }

        reload();
    });
*/


function fetchPageMetaParam(){
    return $output.value;
}

    var $load_content_def_button = document.getElementById('updateContentDef');
var schemaPage = null;
    // Update the schema when the button is clicked
    $load_content_def_button.addEventListener('click',function() {
            var cnt_schema_str = loadPageParams();
            cnt_schema = JSON.parse(cnt_schema_str);
            //setting output schema to page;
            document.getElementById("output_schema").value = cnt_schema_str;
        try {
            ;
        }
        catch(e) {
            alert('Invalid Schema: '+e.message);
            return;
        }

        reload_cnt();
        fillPageAreaInfo();
    });

    var $reloadContent = document.getElementById("reloadContent");
    $reloadContent.addEventListener("click",function(){
        var cnt = document.getElementById("output_cnt").value;
        if(cnt){
            jsoneditor_cnt.setValue(JSON.parse(cnt));
        } 
        return false;
    });

    //验证编辑级别和编辑页面区域：
    $sltPageArea = document.getElementById("sltPageArea");
    $sltPageArea.addEventListener("change",function(){
        //change page area
        var title = this.options[this.selectedIndex].value;
        if(title){           
        for(var i in cnt_schema.properties.pageBlocks.properties){ 
            var path = "root.pageBlocks."+i;
            var o = jsoneditor_cnt.getEditor(path);
            var b = o.toggle_button;
            if(title === i ){
                if(b.innerHTML === '展开'){
                    _fire(b,"click");
                    // b.disabled = false;
                }
                b.disabled = false;
            }
            else{   //not selected area
                if(b.innerHTML === "收起"){
                    _fire(b,'click');
                } 
                    b.disabled = true;
            } 
        }
            //
        }
    });
    function fillPageAreaInfo(){
        sltPageArea.options.length = 0;
        sltPageArea.add(new Option("请选择",""))
        var idx = 0;
        for(var i in cnt_schema.properties.pageBlocks.properties){
            var o = cnt_schema.properties.pageBlocks.properties[i];
            sltPageArea.add(new Option(o.title,i));
            idx++;
        }
    };

    var userLevel = "1";
    $sltEditorLevel = document.getElementById("sltEditorLevel");
    $sltEditorLevel.addEventListener("change",function(){
        //change editor level
        var pageParams = $output.value;
        if(!pageParams){
            alert("请先设置页面参数信息");
            return;
        }
        jsoneditor_cnt.getEditor("root").disable();

        if(this.options[this.selectedIndex].value){
            userLevel = this.options[this.selectedIndex].value;
            var path = "";
            //travel(JSON.parse(pageParams),path);
            var authInfo = new Auth4Level(userLevel,"");
            findAuth4Level(JSON.parse(pageParams),path,authInfo);
            //console.debug(authInfo);
            testAuthInfoVisit(authInfo,"\t","root");
            setEditor4Level(authInfo,"root");
        }
    });


    //设置编辑状态
    function setEditor4Level(authInfo,ppath){
        scanArrayAxises(authInfo,ppath);

        var pp =  authInfo.parentPath;
        pp = ppath +  (pp === ""?"":"."+pp) ;
        for(var fp in authInfo.flatPath){
            // console.debug(preIdens +">" + parentPath + "." + authInfo.flatPath[fp]);
            if(authInfo.arrayAxises > 0){   //如果实例数组存在，需要在数组纬度上展开
                for(var ti =0; ti < authInfo.arrayAxises;ti++){
                    var apth = pp + "." +ti +"." + authInfo.flatPath[fp];
                    // console.debug( apth);
                    var editor = jsoneditor_cnt.getEditor(apth);

                    if(editor)  editor.enable();
                }
            }
            else{
                var apth = pp + "." + authInfo.flatPath[fp];
                // console.debug( apth);
                var editor = jsoneditor_cnt.getEditor(apth);

                if(editor)  editor.enable();
            }
        }

        var i =0;
        for(var a in authInfo.arrayPath){   //处理每个数组类型
            var ai = authInfo.arrayPath[a];
            if(authInfo.arrayAxises > 0){
                for(var ti =0 ; ti < authInfo.arrayAxises;ti ++){   //在数组类型上展开
                    setEditor4Level(ai,pp+"."+ti);    
                }
            }
            else
                setEditor4Level(ai,pp);
        }
    }

     var searchLevel = 100;

    function scanArrayAxises(ai,ppath){
        var pp =  ai.parentPath;
        pp = ppath +  (pp === ""?"":"."+pp) ;
        for(var i =0; i < searchLevel;i++){
            var arrayIdxPath = pp + "." +  i;
            var arrayIns = jsoneditor_cnt.getEditor(arrayIdxPath);
            if(!arrayIns)  break;
            ai.arrayAxises = i+1;

        // console.log("scan array axis :"+ppath + ","+arrayIdxPath);
        } 
    }

    function setArray4Level(ai,ppath){
        var pp =  ai.parentPath;
        pp = ppath +  (pp === ""?"":"."+pp) ;
        for(var i =0; i < searchLevel;i++){
            var arrayIdxPath = pp + "." +  i;
            var arrayIns = jsoneditor_cnt.getEditor(arrayIdxPath);
            if(!arrayIns)   break;

            // for()            
        }
    }



    function testAuthInfoVisit(authInfo,preIdens,parentPath){
        // var idens = 0;
        for(var fp in authInfo.flatPath){
            console.debug(preIdens +">" + parentPath + "." + authInfo.flatPath[fp]);        
        }
        var i =0;
        for(var a in authInfo.arrayPath){
            var ai = authInfo.arrayPath[a];
            var pi = preIdens + "\t" ;
            var pp = parentPath + "."+ai.parentPath + "." + i;
            console.debug(pi + ">"+pp +"."+)
            testAuthInfoVisit(ai,pi,pp);
            i++;
        }
    }

    /**
    **
    **/
    function postReadyFunc(){
        console.log("json editor is ready!");
    }


    //     var metaMark = "bizMeta";
    //     var levelMark = "distLevel";

    // function visitNode(node,path){
    //     if(node){
    //         if(Array.isArray(node)){
    //             var ii = 0;
    //             for(var nn in node){
    //                 visitNode(node[nn],path+"["+ii+"]");
    //                 ii++;
    //             }
    //         }
    //         if(window.isplainobject(node)){
    //             if(node[metaMark] && node[metaMark][levelMark]){
    //                 var lv = node[metaMark][levelMark];
    //                 var pageObjs = document.getElementsByName(path);    
    //                 for(var po in pageObjs){                        
    //                     if(lv === currentLevel){                         
    //                         po.disabled = true;   
    //                     }
    //                     else
    //                         po.disabled = false;
    //                 }
    //             }
    //             else{
    //                 for(var nn in node){
    //                     if(nn === metaMark) return "";
    //                     visitNode(node[nn],path+"["+nn+"]");
    //                 }
    //             }
    //         }
    //         //raw type,return;
    //         return "";
         
    //     }
    // }

</script>
</body>
</html>
